package cn.xuqiudong.demo.mvc.i18n.helper;

import cn.xuqiudong.demo.mvc.i18n.I18nConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 说明: 国际化工具类
 * @see I18nConfig#localeResolver()
 * @author Vic.xu
 * @since 2023/4/19/0019 15:21
 */
public class I18nHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(I18nHelper.class);

    private static MessageSource messageSource;

    private static LocaleResolver localeResolver;

    public static void initI18nHelper(MessageSource messageSource, LocaleResolver sessionLocaleResolver) {
        LOGGER.info("I18nHelper properties init");
        I18nHelper.messageSource = messageSource;
        I18nHelper.localeResolver = sessionLocaleResolver;
    }

    /**
     * 获取国际化 code 对应的message
     *
     * @param code  code
     * @param args args
     * @return msg or key
     */
    public static String getMessage(String code, Object... args) {
        try {
            Locale locale = LocaleContextHolder.getLocale();
            return messageSource.getMessage(code, args, locale);
        } catch (Exception ex) {
            return code;
        }
    }

    /**
     * 设置当前线程中的Locale
     *
     * @param locale Locale
     */
    public static void setLocale(Locale locale) {
        LocaleContextHolder.setLocale(locale);
    }

    /**
     * remove 当前线程中的Locale
     */
    public static void removeLocale() {
        LocaleContextHolder.resetLocaleContext();
    }

    /**
     * 切换local
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param locale Locale.CHINA; Locale.US
     * @return if successful
     */
    public static boolean switchLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        if (localeResolver == null) {
            return false;
        }
        localeResolver.setLocale(request, response, locale);
        return true;
    }

}

